package comits.business.tiers.utilitaires;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

/**
 * An OutputStream that writes contents to a Logger upon each call to flush()
 */
public class LoggingOutputStream extends ByteArrayOutputStream {
    
    private String lineSeparator;
    
    private Logger logger;
    private Level level;
    
    public void initializeLog(){
	    	Dates dat = new Dates();
			//logDates dat = new Dates();
			
			// initialize logging to go to rolling log file
	        LogManager logManager = LogManager.getLogManager();
	        logManager.reset();
	
	        // log file max size 10K, 3 rolling files, append-on-open
	        Handler fileHandler;
			try {
				File f = new File("ComitsLOGS"); 
				f.mkdirs();
				fileHandler = new FileHandler("ComitsLOGS/log_"+ dat.getIntDay()+dat.getMonth()+dat.getYear()+".log",true);
				fileHandler.setFormatter(new SimpleFormatter());
		        Logger.getLogger("").addHandler(fileHandler);
			} catch (SecurityException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			
		// preserve old stdout/stderr streams in case they might be useful
		PrintStream stdout = System.out;
		PrintStream stderr = System.err;
		
		// now rebind stdout/stderr to logger
		Logger logger;
		LoggingOutputStream los;
	
		logger = Logger.getLogger("stdout");
		los = new LoggingOutputStream(logger, StdOutErrLevel.STDOUT);
		System.setOut(new PrintStream(los, true));
		
		logger = Logger.getLogger("stderr");
		los= new LoggingOutputStream(logger, StdOutErrLevel.STDERR);
		System.setErr(new PrintStream(los, true));
    }
    
    /**
     * Constructor
     * @param logger Logger to write to
     * @param level Level at which to write the log message
     */
    private LoggingOutputStream(Logger logger, Level level) {
        super();
        this.logger = logger;
        this.level = level;
        lineSeparator = System.getProperty("line.separator");
    }
    
    public LoggingOutputStream() {
		// TODO Auto-generated constructor stub
	}

	/**
     * upon flush() write the existing contents of the OutputStream to the logger as 
     * a log record.
     * @throws java.io.IOException in case of error
     */
    public void flush() throws IOException {

        String record;
        synchronized(this) {
            super.flush();
            record = this.toString();
            super.reset();
        }
        
        if (record.length() == 0 || record.equals(lineSeparator)) {
            // avoid empty records
            return;
        }

        logger.logp(level, "", "", record);
    }
}